import datetime
import os

CHAR_ENCODING = 'ISO-8859-1'

from django.utils.encoding import smart_str

os.environ['DJANGO_SETTINGS_MODULE'] = 'ceemtu.settings'

from ceemtu.cetmusic.models import *
from ceemtu.cetcore.models import *

class MusicPatternMethods:

    def get_album_cover(self, pattern, _file_entry):
        "Tries to find a suitable album cover for an album."
        return False
    
    def generate_song_from_entry(self, pattern, _file_entry):
        "Creates a song-entry based on a file-entry."
        metadata = _file_entry.get_metadata(flatten = True)

        s = metadata.get('TITLE', metadata.get('generic extractor - Title'))
        if type(s) == types.StringType:
            s = unicode(s, CHAR_ENCODING)
        metadata['TITLE'] = s

        s = metadata.get('ARTIST', metadata.get('generic extractor - Author'))
        if type(s) == types.StringType:
            s = unicode(s, CHAR_ENCODING)
        metadata['ARTIST'] = s

        s = metadata.get('ALBUM', metadata.get('generic extractor - Album'))
        if type(s) == types.StringType:
            s = unicode(s, CHAR_ENCODING)
        metadata['ALBUM'] = s

        try:
            old_song = Song.objects.get(file_entry = _file_entry)[0]
            old_song.title = metadata.get('TITLE')
            old_song.artist = metadata.get('ARTIST')
            old_song.album = metadata.get('ALBUM')
            old_song.release_year = metadata.get('YEAR', metadata.get('generic extractor - Creation date', None))
            old_song.bitrate = metadata.get('BITRATE', metadata.get('generic extractor - Bit rate'))
            old_song.genre = metadata.get('GENRE')
            old_song.minutes = int(metadata.get('MM', 0))
            old_song.seconds = int(metadata.get('SS', 0))
            old_song.save()
        except:
            new_song = Song(
                file_entry = _file_entry,
                title = metadata.get('TITLE'),
                artist = metadata.get('ARTIST'),
                album = metadata.get('ALBUM'),
                release_year = metadata.get('YEAR', metadata.get('generic extractor - Creation date', None)),
                bitrate = metadata.get('BITRATE', metadata.get('generic extractor - Bit rate')),
                genre = metadata.get('GENRE'),
                minutes = int(metadata.get('MM', 0)),
                seconds = int(metadata.get('SS', 0)),
                date_added = datetime.datetime.today()
            )
            new_song.save()
            return False